import axios from 'axios';   // Axios库
// Element Plus组件库
import { ElMessage, ElLoading } from 'element-plus';
import router from '@/router';
import { useUserStore } from '@/stores/userStore'
// import { getToken, removeToken } from './auth';
import { getErrorMsg } from './error-code';
// 默认配置
// import.meta.env.VITE_APP_BASE_API
// const  baseURL
const DEFAULT_CONFIG = {
  baseURL: "http://localhost:80/api",
  timeout: 50000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
};

// 创建axios实例
const service = axios.create(DEFAULT_CONFIG);

// 全局请求配置
let globalConfig = {
  showLoading: true,
  loadingText: '加载中...',
  showError: true
};

// 加载实例
let loadingInstance = null;

// 显示加载动画
const showLoading = (text) => {
  loadingInstance = ElLoading.service({
    lock: true,
    text: text || globalConfig.loadingText,
    background: 'rgba(0, 0, 0, 0.1)'
  });
};

// 隐藏加载动画
const hideLoading = () => {
  loadingInstance && loadingInstance.close();
};
// auth.js
 const getToken = () => {
  return localStorage.getItem('token');
};
 const setToken = (token) => {
  localStorage.setItem('token', token);
};

 const removeToken = () => {
  localStorage.removeItem('token');
};    
// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 合并配置
    const reqConfig = { ...config };
    if (reqConfig.custom) {
      reqConfig.headers.showLoading = reqConfig.custom.showLoading !== undefined 
        ? reqConfig.custom.showLoading 
        : globalConfig.showLoading;
      reqConfig.headers.showError = reqConfig.custom.showError !== undefined 
        ? reqConfig.custom.showError 
        : globalConfig.showError;
    } else {
      reqConfig.headers.showLoading = globalConfig.showLoading;
      reqConfig.headers.showError = globalConfig.showError;
    }
    
    // 显示加载动画
    if (reqConfig.headers.showLoading) {
      showLoading(reqConfig.headers.loadingText);
    }
    
    // 添加token
    const token = getToken();
    if (token) {
      reqConfig.headers['Authorization'] = `Bearer ${token}`;
    }
    
    return reqConfig;
  },
  (error) => {
    // 隐藏加载动画
    hideLoading();
    console.log(error); // 用于调试
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 隐藏加载动画
    if (response.config.headers.showLoading) {
      hideLoading();
    }
    
    const res = response.data;
    // 处理业务错误
    if (res.code !== 200) {
      if (response.config.headers.showError) {
        ElMessage({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        });
      }
      
      // 处理特殊错误码
      if (res.code === 401) {
        // 清除token并跳转到登录页
        removeToken();
        router.push('/login');
      }
      
      return Promise.reject(new Error(res.message || 'Error'));
    } else {
      //请求成功
     // console.log("---",response);
      return res;
    }
  },
  (error) => {
    // 隐藏加载动画
    if (error.config && error.config.headers.showLoading) {
      hideLoading();
    }
    
    // 处理HTTP错误
    const errorMsg = getErrorMsg(error);
    console.log('err' + error); // 用于调试
    
    if (error.config.headers.showError) {
      ElMessage({
        message: errorMsg,
        type: 'error',
        duration: 5 * 1000
      });
    }
    
    // 处理特殊HTTP状态码
    if (error.response && error.response.status === 401) {
      // 清除token并跳转到登录页
      removeToken();
      router.push('/login');
    }
    
    return Promise.reject(error);
  }
);

// 设置全局配置
export const setGlobalConfig = (config) => {
  globalConfig = { ...globalConfig, ...config };
};

// 封装请求方法
const request = {
  get(url, params = {}, config = {}) {
    return service({
      url,
      method: 'get',
      params,
      ...config
    });
  },
  
  post(url, data = {}, config = {}) {
    return service({
      url,
      method: 'post',
      data,
      ...config
    });
  },
  
  put(url, data = {}, config = {}) {
    return service({
      url,
      method: 'put',
      data,
      ...config
    });
  },
  
  delete(url, params = {}, config = {}) {
    return service({
      url,
      method: 'delete',
      params,
      ...config
    });
  },
  
  upload(url, file, config = {}) {
    const formData = new FormData();
    formData.append('file', file);
    
    return service({
      url,
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      ...config
    });
  }
};

export default request;    